package io.mft.runtime.config.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.mft.commons.config.ConfigProvider;
import io.mft.commons.config.datasource.DSConfig;
import io.mft.commons.config.datasource.DSConfigSource;
import io.mft.commons.config.datasource.DatasourceConfig;
import io.mft.commons.exception.MFTException;
import io.mft.runtime.config.ConfigLoader;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ApplicationConfigMFTDatasourceLoader implements ConfigLoader<DSConfig> {

	static boolean warn=false;
	@Override
	public DSConfig load(String appId) {
		DSConfig dsConfig=new DSConfig();
		List<ClassLoader> classLoaders=ConfigProvider.getConfigClassLoaders();
		Map<String, ClassLoader> classLoaderMap=new HashMap<String, ClassLoader>();
		classLoaders.forEach(classLoader->{
			try {
				Map<String, Object> dsConfigMap=ConfigProvider.getConfigObject(classLoader, "dsConfig");
				if (dsConfigMap==null) {
					if (!warn) {
						log.warn("应用插件["+classLoader.getResource(".").getPath()+"]数据源未配置,请检查是否忽略!!!!!!!!!!!!!!!");
						warn=true;
					}
				}else {
					JSONObject jsonObject=JSONUtil.parseObj(dsConfigMap);
					DSConfig t=jsonObject.toBean(DSConfig.class);
					t.init();
					t.keySet().forEach(key->{
						try {
							if (!dsConfig.containsKey(key)) {
								dsConfig.put(key, t.get(key));
							}else {
								DSConfigSource orginDsConfigSource=dsConfig.get(key);
								Map<String, DatasourceConfig> orginDatasourceConfigMap=orginDsConfigSource.datasourceConfigMap();
								DSConfigSource newDsConfigSource=t.get(key);
								if (newDsConfigSource.getDatasources()!=null) {
									newDsConfigSource.getDatasources().forEach(datasourceConfig->{
										try {
											String dk=key+"."+datasourceConfig.getId();
											if (orginDatasourceConfigMap.containsKey(datasourceConfig.getId())) {
												StringBuilder msg=new StringBuilder();
												msg.append("当前数据源["+datasourceConfig.getId()+"]归属应用目录["+classLoader.getResource(".").getPath()+"]");
												msg.append("存在于应用目录["+classLoaderMap.get(dk).getResource(".").getPath()+"]");
												throw new MFTException(msg.toString());													
											}
											
											orginDsConfigSource.getDatasources().add(datasourceConfig);
											classLoaderMap.put(dk, classLoader);											
										} catch (MFTException e) {
											log.error("",e);
										}catch (Exception e) {
											log.error("应用插件["+classLoader.getResource(".").getPath()+"]数据源["+datasourceConfig.getId()+"]解析处理异常",e);
										}
									});
								}
							}
						} catch (Exception e) {
							log.error("应用插件["+classLoader.getResource(".").getPath()+"]数据源类型["+key+"]解析异常",e);
						}
					});
				}

			} catch (Exception e) {
				log.error("应用插件["+classLoader.getResource(".").getPath()+"]数据源解析异常",e);
			}
		});
		return dsConfig;
	}

	
}
